﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MesProjectWinform.Public.Common;
using Newtonsoft.Json.Linq;
using MesProjectWinform.BasicData.Entity;
using Newtonsoft.Json;
using System.Net.Http;
using System.Web;
using System.IO;
using DevExpress.XtraSplashScreen;
using System.Globalization; // 添加格式化所需的命名空间

namespace MesProjectWinform.BasicData.基础实现.chanpin
{
    public partial class chanpin : DevExpress.XtraEditors.XtraForm
    {
        // API服务端口号
        private const string ApiBaseUrl = "http://47.110.243.157:5052/";
        
        // 分页参数
        private int pageIndex = 1;
        private int pageSize = 2;
        private int totalCount = 0;

        public chanpin()
        {
            InitializeComponent();
            
            // 设置窗体居中显示
            this.StartPosition = FormStartPosition.CenterScreen;

            // 初始化分页控件
            InitPagination();

            // 初始化物料群组下拉框
            InitMaterialGroupComboBox();
            
            // 绑定按钮事件
            SetupButtonEvents();

            // 设置GridView列
            ConfigureGridViewColumns();

            // 初始化时加载数据
            LoadData();
        }
        
        /// <summary>
        /// 设置按钮事件绑定
        /// </summary>
        private void SetupButtonEvents()
        {
            try 
            {
                // 绑定修改按钮事件
                if (repositoryItemButtonEdit1 != null)
                {
                    repositoryItemButtonEdit1.ButtonClick -= repositoryItemButtonEdit1_ButtonClick;
                    repositoryItemButtonEdit1.ButtonClick += repositoryItemButtonEdit1_ButtonClick;
                    repositoryItemButtonEdit1.Buttons[0].Caption = "修改";
                    repositoryItemButtonEdit1.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                }
                
                // 绑定删除按钮事件
                if (repositoryItemButtonEdit2 != null)
                {
                    repositoryItemButtonEdit2.ButtonClick -= repositoryItemButtonEdit2_ButtonClick;
                    repositoryItemButtonEdit2.ButtonClick += repositoryItemButtonEdit2_ButtonClick;
                    repositoryItemButtonEdit2.Buttons[0].Caption = "删除";
                    repositoryItemButtonEdit2.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                }
                
                Console.WriteLine("按钮事件绑定成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"按钮事件绑定异常: {ex.Message}");
                XtraMessageBox.Show($"按钮事件绑定异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitPagination()
        {
            // 创建页大小下拉框
            ComboBoxEdit pageSizeCombo = new ComboBoxEdit();
            pageSizeCombo.Properties.Items.AddRange(new object[] { 2, 10, 20, 50, 100 });
            pageSizeCombo.SelectedIndex = 0;
            pageSizeCombo.Width = 60;
            pageSizeCombo.EditValueChanged += PageSizeCombo_EditValueChanged;

            // 创建首页按钮
            SimpleButton btnFirst = new SimpleButton();
            btnFirst.Text = "首页";
            btnFirst.Width = 60;
            btnFirst.Click += BtnFirst_Click;

            // 创建尾页按钮
            SimpleButton btnLast = new SimpleButton();
            btnLast.Text = "尾页";
            btnLast.Width = 60;
            btnLast.Click += BtnLast_Click;

            // 创建页码标签
            LabelControl lblPageInfo = new LabelControl();
            lblPageInfo.Name = "lblPageInfo";
            lblPageInfo.Text = "0/0";
            lblPageInfo.AutoSize = true;
            lblPageInfo.Padding = new Padding(5, 3, 5, 0);

            // 创建总记录数标签
            LabelControl lblTotalCount = new LabelControl();
            lblTotalCount.Name = "lblTotalCount";
            lblTotalCount.Text = "共0条记录";
            lblTotalCount.AutoSize = true;
            lblTotalCount.Padding = new Padding(5, 3, 5, 0);

            // 创建页大小标签
            LabelControl lblPageSize = new LabelControl();
            lblPageSize.Text = "每页显示:";
            lblPageSize.AutoSize = true;
            lblPageSize.Padding = new Padding(5, 3, 5, 0);

            // 添加控件到窗体底部
            FlowLayoutPanel paginationPanel = new FlowLayoutPanel();
            paginationPanel.Dock = DockStyle.Bottom;
            paginationPanel.Height = 40;
            paginationPanel.Padding = new Padding(5);
            paginationPanel.FlowDirection = FlowDirection.LeftToRight;

            // 添加控件到面板
            paginationPanel.Controls.Add(btnFirst);
            paginationPanel.Controls.Add(button4); // 上一页按钮
            paginationPanel.Controls.Add(lblPageInfo);
            paginationPanel.Controls.Add(button5); // 下一页按钮
            paginationPanel.Controls.Add(btnLast);
            paginationPanel.Controls.Add(lblTotalCount);
            paginationPanel.Controls.Add(lblPageSize);
            paginationPanel.Controls.Add(pageSizeCombo);

            // 添加面板到窗体
            this.Controls.Add(paginationPanel);

            // 调整原有按钮宽度和样式
            button4.Width = 60;
            button4.Text = "上一页";
            button5.Width = 60;
            button5.Text = "下一页";
        }

        /// <summary>
        /// 初始化物料群组下拉框
        /// </summary>
        private void InitMaterialGroupComboBox()
        {
            // 添加物料群组选项
            comboBox1.Items.Clear();
            comboBox1.Items.Add(" ");
            comboBox1.Items.Add("原材料");
            comboBox1.Items.Add("半成品");
            comboBox1.Items.Add("成品");
            comboBox1.Items.Add("其他");
            comboBox1.SelectedIndex = 0;
        }

        /// <summary>
        /// 页大小改变事件
        /// </summary>
        private void PageSizeCombo_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                ComboBoxEdit combo = sender as ComboBoxEdit;
                if (combo != null && int.TryParse(combo.EditValue.ToString(), out int newPageSize))
                {
                    pageSize = newPageSize;
                    pageIndex = 1; // 重置为第一页
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"修改页容量异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 首页按钮点击事件
        /// </summary>
        private void BtnFirst_Click(object sender, EventArgs e)
        {
            try
            {
                if (pageIndex > 1)
                {
                    pageIndex = 1;
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"翻页操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 尾页按钮点击事件
        /// </summary>
        private void BtnLast_Click(object sender, EventArgs e)
        {
            try
            {
                int totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
                if (pageIndex < totalPages)
                {
                    pageIndex = totalPages;
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"翻页操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 检查API返回的JSON数据结构与Model类的属性是否匹配
        /// </summary>
        private void CheckJsonToModelMapping(string jsonData)
        {
            try
            {
                // 解析JSON对象
                JObject jsonObj = JObject.Parse(jsonData);
                
                // 检查基本结构
                if (jsonObj["Code"] == null || jsonObj["Message"] == null || jsonObj["Data"] == null || jsonObj["TotalCount"] == null)
                {
                    XtraMessageBox.Show("API返回的JSON结构与ProductItemDto不匹配", "结构错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 获取Data数组
                JArray dataArray = jsonObj["Data"] as JArray;
                if (dataArray == null || dataArray.Count == 0)
                {
                    XtraMessageBox.Show("API返回的Data为空数组或不是数组", "数据错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                // 获取第一条数据
                JObject firstItem = dataArray[0] as JObject;
                if (firstItem == null)
                {
                    XtraMessageBox.Show("无法获取第一条数据", "数据错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                // 获取ProductItemModel的所有属性
                var properties = typeof(ProductItemModel).GetProperties();
                
                // 创建一个字符串构建器来收集属性映射信息
                StringBuilder mappingInfo = new StringBuilder();
                mappingInfo.AppendLine("JSON与Model属性映射情况：");
                
                // 检查每个属性是否在JSON中存在
                foreach (var prop in properties)
                {
                    // 检查JSON中是否有对应的属性（不区分大小写）
                    bool found = false;
                    string jsonPropName = string.Empty;
                    
                    foreach (var jsonProp in firstItem.Properties())
                    {
                        if (string.Equals(jsonProp.Name, prop.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            found = true;
                            jsonPropName = jsonProp.Name;
                            break;
                        }
                    }
                    
                    if (found)
                    {
                        mappingInfo.AppendLine($"✓ 属性 {prop.Name} 在JSON中找到对应项: {jsonPropName}");
                    }
                    else
                    {
                        mappingInfo.AppendLine($"✗ 属性 {prop.Name} 在JSON中未找到对应项");
                    }
                }
                
                // 显示映射信息
                XtraMessageBox.Show(mappingInfo.ToString(), "属性映射检查", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"检查JSON映射时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载产品物料数据
        /// </summary>
        private async void LoadData()
        {
            try
            {
                // 构建查询参数
                string productTypeValue = string.Empty;
                if (comboBox1.SelectedIndex > 0)
                {
                    // 将选择的物料群组转换为对应的数字类型
                    switch (comboBox1.SelectedItem.ToString())
                    {
                        case "原材料":
                            productTypeValue = "1";
                            break;
                        case "半成品":
                            productTypeValue = "2";
                            break;
                        case "成品":
                            productTypeValue = "3";
                            break;
                        case "其他":
                            productTypeValue = "4";
                            break;
                    }
                    Console.WriteLine($"转换物料类型: \"{comboBox1.SelectedItem}\" -> {productTypeValue}");
                }

                // 获取编号和名称的查询值
                string productCode = textEdit1.Text.Trim();
                string productName = textEdit2.Text.Trim();
                
                // 查询前记录日志
                Console.WriteLine($"开始查询: 页码={pageIndex}, 每页数量={pageSize}");
                Console.WriteLine($"查询条件: 产品类型值={productTypeValue}, 产品编号=\"{productCode}\", 产品名称=\"{productName}\"");

                // 构建API URL基础部分，包含分页参数
                string url = $"http://47.110.243.157:5052/api/ProductItem/GetProductItem?pageindex={pageIndex}&pagesize={pageSize}";
                
                // 添加产品类型参数
                if (!string.IsNullOrEmpty(productTypeValue))
                {
                    url += $"&Producttype={HttpUtility.UrlEncode(productTypeValue)}";
                    Console.WriteLine($"添加产品类型查询条件: Producttype={productTypeValue}");
                }
                
                // 添加产品编号查询参数
                if (!string.IsNullOrEmpty(productCode))
                {
                    url += $"&Productitemcode={HttpUtility.UrlEncode(productCode)}";
                    Console.WriteLine($"添加产品编码查询条件: Productitemcode={productCode}");
                }
                
                // 添加产品名称查询参数
                if (!string.IsNullOrEmpty(productName))
                {
                    url += $"&Productitemname={HttpUtility.UrlEncode(productName)}";
                    Console.WriteLine($"添加产品名称查询条件: Productitemname={productName}");
                }
                
                Console.WriteLine($"完整请求URL: {url}");

                try
                {
                    using (HttpClient client = new HttpClient())
                    {
                        // 设置超时时间
                        client.Timeout = TimeSpan.FromSeconds(30);
                        
                        // 记录请求开始时间
                        DateTime startTime = DateTime.Now;
                        
                        // 发送GET请求
                        HttpResponseMessage response = await client.GetAsync(url);
                        
                        // 记录请求结束时间
                        TimeSpan requestTime = DateTime.Now - startTime;
                        Console.WriteLine($"API请求耗时: {requestTime.TotalMilliseconds}ms");
                        
                        // 检查响应状态
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            string responseContent = await response.Content.ReadAsStringAsync();
                            Console.WriteLine("API响应成功，开始解析数据");
                            
                            // 反序列化响应结果
                            var result = JsonConvert.DeserializeObject<ProductItemDto>(responseContent);
                            
                            if (result == null)
                            {
                                XtraMessageBox.Show("无法解析返回的数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            
                            if (result.Code != "200")
                            {
                                XtraMessageBox.Show($"获取数据失败: {result.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            
                            // 更新总记录数
                            totalCount = result.TotalCount;
                            Console.WriteLine($"获取到总记录数: {totalCount}");
                            
                            // 绑定数据到GridControl
                            gridControl1.DataSource = result.PageData;
                            Console.WriteLine($"成功加载数据: {(result.PageData != null ? result.PageData.Count : 0)}条记录");
                            
                            // 更新分页信息
                            UpdatePageInfo();
                        }
                        else
                        {
                            // 读取错误响应
                            string errorContent = await response.Content.ReadAsStringAsync();
                            XtraMessageBox.Show($"获取数据失败，HTTP状态码: {response.StatusCode}\n{errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Console.WriteLine($"API请求失败: {response.StatusCode}, 响应内容: {errorContent}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"网络请求异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Console.WriteLine($"网络请求异常: {ex.Message}\n{ex.StackTrace}");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"加载数据异常: {ex.Message}\n{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 更新页码信息
        /// </summary>
        private void UpdatePageInfo()
        {
            int totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

            // 更新为简单标题，不包含页码信息
            this.Text = "产品物料管理";

            // 更新分页信息标签
            LabelControl lblPageInfo = this.Controls.Find("lblPageInfo", true).FirstOrDefault() as LabelControl;
            if (lblPageInfo != null)
            {
                lblPageInfo.Text = $"{pageIndex}/{totalPages}";
            }

            // 更新总记录数标签
            LabelControl lblTotalCount = this.Controls.Find("lblTotalCount", true).FirstOrDefault() as LabelControl;
            if (lblTotalCount != null)
            {
                lblTotalCount.Text = $"共{totalCount}条记录";
            }

            // 设置按钮状态
            SimpleButton btnFirst = this.Controls.OfType<SimpleButton>().FirstOrDefault(b => b.Text == "首页");
            SimpleButton btnLast = this.Controls.OfType<SimpleButton>().FirstOrDefault(b => b.Text == "尾页");

            if (btnFirst != null) btnFirst.Enabled = pageIndex > 1;
            if (btnLast != null) btnLast.Enabled = pageIndex < totalPages;
            button4.Enabled = pageIndex > 1;
            button5.Enabled = pageIndex < totalPages;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取查询条件，根据需要打印日志方便调试
                string productCode = textEdit1.Text.Trim();
                string productName = textEdit2.Text.Trim();
                string productType = comboBox1.SelectedIndex > 0 ? comboBox1.SelectedItem.ToString() : string.Empty;
                
                Console.WriteLine($"执行查询: 产品编号=\"{productCode}\", 产品名称=\"{productName}\", 产品类型=\"{productType}\"");
                
                pageIndex = 1; // 重置为第一页
                LoadData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                if (pageIndex > 1)
                {
                    pageIndex--;
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"翻页操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                int totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
                if (pageIndex < totalPages)
                {
                    pageIndex++;
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"翻页操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 立即显示反馈，告知用户点击已被捕获
                Console.WriteLine("修改按钮被点击");
                Cursor = Cursors.WaitCursor;
                // 获取当前选中行对应的数据对象
                var view = gridView1;
                if (view == null || view.RowCount == 0)
                {
                    XtraMessageBox.Show("没有可选择的数据记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                
                // 获取选中行的句柄和ID
                int rowHandle = view.FocusedRowHandle;
                if (rowHandle < 0)
                {
                    XtraMessageBox.Show("请选择要修改的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                
                long id = 0;
                try
                {
                    // 尝试获取ID值
                    object idValue = view.GetRowCellValue(rowHandle, "Id");
                    if (idValue != null)
                    {
                        id = Convert.ToInt64(idValue);
                    }
                    
                    if (id <= 0)
                    {
                        XtraMessageBox.Show("无效的记录ID", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"获取记录ID失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 获取产品名称用于日志记录
                string productName = "";
                try
                {
                    object nameValue = view.GetRowCellValue(rowHandle, "Productitemname");
                    if (nameValue != null)
                    {
                        productName = nameValue.ToString();
                    }
                }
                catch { }
                
                Console.WriteLine($"准备修改产品: ID={id}, 名称={productName}");

                try
                {
                    // 创建编辑窗体并传递产品ID
                    pinup editForm = new pinup(id);
                    
                    // 显示窗体，如果修改成功则刷新数据
                    if (editForm.ShowDialog() == DialogResult.OK)
                    {
                        // 刷新数据
                        Console.WriteLine("修改成功，正在刷新数据...");
                        LoadData();
                    }
                    else
                    {
                        Console.WriteLine("用户取消了修改操作");
                    }
                }
                catch (Exception formEx)
                {
                    Console.WriteLine($"创建或显示编辑窗体异常: {formEx.Message}\n{formEx.StackTrace}");
                    XtraMessageBox.Show($"打开编辑窗口失败: {formEx.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"修改操作异常: {ex.Message}\n{ex.StackTrace}");
                XtraMessageBox.Show($"修改操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 物料群组下拉框选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                // 如果不是选择第一项（请选择群组类型），则自动触发查询
                if (comboBox1.SelectedIndex > 0)
                {
                    pageIndex = 1; // 重置为第一页
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 立即显示反馈，告知用户点击已被捕获
                Console.WriteLine("删除按钮被点击");
                Cursor = Cursors.WaitCursor;
                // 获取当前选中行对应的数据对象
                var view = gridView1;
                if (view == null || view.RowCount == 0)
                {
                    XtraMessageBox.Show("没有可选择的数据记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                
                // 获取选中行的句柄和ID
                int rowHandle = view.FocusedRowHandle;
                if (rowHandle < 0)
                {
                    XtraMessageBox.Show("请选择要删除的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                
                long id = 0;
                try
                {
                    // 尝试获取ID值
                    object idValue = view.GetRowCellValue(rowHandle, "Id");
                    if (idValue != null)
                    {
                        id = Convert.ToInt64(idValue);
                    }
                    
                    if (id <= 0)
                    {
                        XtraMessageBox.Show("无效的记录ID", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"获取记录ID失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 获取产品名称用于日志记录
                string productName = "";
                try
                {
                    object nameValue = view.GetRowCellValue(rowHandle, "Productitemname");
                    if (nameValue != null)
                    {
                        productName = nameValue.ToString();
                    }
                }
                catch { }

                // 确认删除
                DialogResult result = XtraMessageBox.Show($"确定要删除该记录吗？\nID: {id}\n名称: {productName}", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result != DialogResult.Yes)
                    return;

                // 获取按钮控件
                var buttonEdit = sender as ButtonEdit;
                
                // 禁用删除按钮，防止重复点击
                if (buttonEdit != null)
                    buttonEdit.Enabled = false;
                
                // 定义在外部作用域，以便在整个方法中访问
                bool isSuccess = false;
                string errorMessage = "删除失败";
                
                try
                {
                    // 显示等待提示
                    Cursor = Cursors.WaitCursor;
                    
                    // 构建API URL
                    string url = $"api/ProductItem/DeleteProductItem?id={id}";
                    Console.WriteLine($"执行删除操作: ID={id}, 名称={productName}, URL={url}");
                    
                    // 使用直接的HttpClient调用API
                    using (HttpClient client = new HttpClient())
                    {
                        // 设置基础地址
                        client.BaseAddress = new Uri(ApiBaseUrl);
                        
                        // 发送PUT请求
                        HttpResponseMessage response = await client.PutAsync(url, null);
                        
                        // 读取响应内容
                        string responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"删除操作响应: {responseContent}");
                        
                        // 检查响应状态
                        if (response.IsSuccessStatusCode)
                        {
                            try
                            {
                                // 尝试解析JSON响应
                                JObject jObj = JObject.Parse(responseContent);
                                string code = jObj["Code"]?.ToString() ?? jObj["code"]?.ToString();
                                
                                // 检查响应状态码
                                if (code == "200")
                                {
                                    isSuccess = true;
                                }
                                else
                                {
                                    // 获取错误消息
                                    errorMessage = jObj["Message"]?.ToString() ?? jObj["message"]?.ToString() ?? "删除失败";
                                }
                            }
                            catch (Exception parseEx)
                            {
                                Console.WriteLine($"解析删除响应异常: {parseEx.Message}");
                                errorMessage = $"解析响应失败: {parseEx.Message}";
                            }
                        }
                        else
                        {
                            errorMessage = $"请求失败，状态码: {response.StatusCode}";
                        }
                    }
                }
                finally
                {
                    // 恢复删除按钮状态
                    if (buttonEdit != null)
                        buttonEdit.Enabled = true;
                        
                    // 恢复光标
                    Cursor = Cursors.Default;
                }
                
                // 根据结果执行相应操作
                if (isSuccess)
                {
                    XtraMessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 重置到第一页，并刷新数据
                    pageIndex = 1;
                    LoadData();
                }
                else
                {
                    XtraMessageBox.Show($"删除失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除操作异常: {ex.Message}\n{ex.StackTrace}");
                XtraMessageBox.Show($"删除操作发生异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 确保恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click_1(object sender, EventArgs e)
        {
            try
            {
                // 打开新增产品物料窗体
                pinup addForm = new pinup();
                
                // 如果新增成功，刷新数据
                if (addForm.ShowDialog() == DialogResult.OK)
                {
                    // 刷新数据
                    pageIndex = 1; // 重置为第一页
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"打开新增窗口失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 配置GridView列
        /// </summary>
        private void ConfigureGridViewColumns()
        {
            try
            {
                // 清除现有列
                gridView1.Columns.Clear();

                // 添加序号列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "序号",
                    FieldName = "Id",
                    Visible = true,
                    VisibleIndex = 0,
                    Width = 60
                });

                // 添加编码列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "编号",
                    FieldName = "Productitemcode",
                    Visible = true,
                    VisibleIndex = 1,
                    Width = 100
                });

                // 添加名称列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "名称",
                    FieldName = "Productitemname",
                    Visible = true,
                    VisibleIndex = 2,
                    Width = 120
                });

                // 添加规格型号列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "规格型号",
                    FieldName = "Productitemspecification",
                    Visible = true,
                    VisibleIndex = 3,
                    Width = 100
                });

                // 添加单位列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "单位",
                    FieldName = "Productitemunit",
                    Visible = true,
                    VisibleIndex = 4,
                    Width = 60
                });

                // 添加预警值列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "预警值",
                    FieldName = "Productitemwarningvalue",
                    Visible = true,
                    VisibleIndex = 5,
                    Width = 60
                });

                // 添加群组名称列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "群组名称",
                    FieldName = "Materialgroupid",
                    Visible = true,
                    VisibleIndex = 6,
                    Width = 100
                });

                // 添加群组类型列
                DevExpress.XtraGrid.Columns.GridColumn groupTypeColumn = new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "群组类型",
                    FieldName = "Producttype",
                    Visible = true,
                    VisibleIndex = 7,
                    Width = 80
                };
                
                // 自定义显示逻辑，使用valueCallback方法转换数字为文字
                groupTypeColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                groupTypeColumn.DisplayFormat.Format = new CustomProductTypeFormatter();
                gridView1.Columns.Add(groupTypeColumn);

                // 添加描述列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "描述",
                    FieldName = "Productitemdescribe",
                    Visible = true,
                    VisibleIndex = 8,
                    Width = 150
                });

                // 添加创建时间列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "创建时间",
                    FieldName = "CreatedTime",
                    Visible = true,
                    VisibleIndex = 9,
                    Width = 120
                });

                // 添加创建人列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "创建人",
                    FieldName = "CreatedBy",
                    Visible = true,
                    VisibleIndex = 10,
                    Width = 80
                });

                // 添加修改时间列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "修改时间",
                    FieldName = "UpdatedTime",
                    Visible = true,
                    VisibleIndex = 11,
                    Width = 120
                });

                // 添加操作列（修改按钮）
                DevExpress.XtraGrid.Columns.GridColumn editColumn = new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "修改",
                    VisibleIndex = 12,
                    Width = 60,
                    Visible = true,
                    UnboundType = DevExpress.Data.UnboundColumnType.Object
                };
                
                // 确保修改按钮设置正确
                if (repositoryItemButtonEdit1 == null)
                {
                    repositoryItemButtonEdit1 = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
                    repositoryItemButtonEdit1.AutoHeight = false;
                    repositoryItemButtonEdit1.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                    repositoryItemButtonEdit1.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
                    repositoryItemButtonEdit1.Buttons[0].Caption = "修改";
                    repositoryItemButtonEdit1.ButtonsStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple;
                    repositoryItemButtonEdit1.ButtonClick += repositoryItemButtonEdit1_ButtonClick;
                }
                
                editColumn.ColumnEdit = repositoryItemButtonEdit1;
                gridView1.Columns.Add(editColumn);

                // 添加操作列（删除按钮）
                DevExpress.XtraGrid.Columns.GridColumn deleteColumn = new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "删除",
                    VisibleIndex = 13,
                    Width = 60,
                    Visible = true,
                    UnboundType = DevExpress.Data.UnboundColumnType.Object
                };
                
                // 确保删除按钮设置正确
                if (repositoryItemButtonEdit2 == null)
                {
                    repositoryItemButtonEdit2 = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
                    repositoryItemButtonEdit2.AutoHeight = false;
                    repositoryItemButtonEdit2.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                    repositoryItemButtonEdit2.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
                    repositoryItemButtonEdit2.Buttons[0].Caption = "删除";
                    repositoryItemButtonEdit2.ButtonsStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple;
                    repositoryItemButtonEdit2.ButtonClick += repositoryItemButtonEdit2_ButtonClick;
                }
                
                deleteColumn.ColumnEdit = repositoryItemButtonEdit2;
                gridView1.Columns.Add(deleteColumn);

                // 设置GridView的选项
                gridView1.OptionsBehavior.Editable = false;
                gridView1.OptionsView.ShowGroupPanel = false;
                gridView1.OptionsView.ShowIndicator = false;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"配置网格列异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 实现导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button3_Click(object sender, EventArgs e)
        {
            try
            {
                // 显示保存对话框，让用户选择保存位置
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";
                saveFileDialog.Title = "导出Excel";
                saveFileDialog.FileName = $"产品物料数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                
                if (saveFileDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                
                // 显示等待提示
                XtraMessageBox.Show("正在导出数据，请稍候...", "导出中", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
                // 构建查询参数
                string materialGroup = string.Empty;
                if (comboBox1.SelectedIndex > 0)
                {
                    materialGroup = comboBox1.SelectedItem.ToString();
                }

                string searchText = textEdit1.Text.Trim();

                // 构建API URL
                string url = "api/ProductItem/ExportProductItemToExcel";
                
                // 添加可选查询参数
                if (!string.IsNullOrEmpty(materialGroup))
                {
                    url += $"?materialGroup={System.Web.HttpUtility.UrlEncode(materialGroup)}";
                }
                
                if (!string.IsNullOrEmpty(searchText))
                {
                    url += string.IsNullOrEmpty(materialGroup) ? "?" : "&";
                    url += $"searchText={System.Web.HttpUtility.UrlEncode(searchText)}";
                }

                // 临时保存原始BaseUrl
                string originalBaseUrl = Properties.Settings.Default.BaseUrl;
                try
                {
                    // 临时修改BaseUrl为定义的API端口
                    Properties.Settings.Default.BaseUrl = ApiBaseUrl;
                    
                    // 创建HttpClient实例
                    using (HttpClient client = new HttpClient())
                    {
                        // 设置基础地址
                        client.BaseAddress = new Uri(ApiBaseUrl);
                        // 设置超时时间
                        client.Timeout = TimeSpan.FromMinutes(5); // 导出可能需要更长时间
                        
                        // 发送GET请求
                        HttpResponseMessage response = await client.GetAsync(url);
                        
                        // 检查响应状态
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容为字节数组
                            byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
                            
                            // 将字节数组保存为文件
                            File.WriteAllBytes(saveFileDialog.FileName, fileBytes);
                            
                            XtraMessageBox.Show("导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            string errorContent = await response.Content.ReadAsStringAsync();
                            XtraMessageBox.Show($"导出失败: {response.StatusCode}, {errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                finally
                {
                    // 恢复原始BaseUrl
                    Properties.Settings.Default.BaseUrl = originalBaseUrl;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"导出异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 修改删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.Caption == "修改")
            {
                EditSelectedRow(e.RowHandle);
            }
            if (e.Column.Caption == "删除")
            {
                DeleteSelectedRow(e.RowHandle);
            }
        }
        /// <summary>
        /// 封装修改操作
        /// </summary>
        /// <param name="rowHandle">选中行的句柄</param>
        private void EditSelectedRow(int rowHandle)
        {
            try
            {
                // 立即显示反馈，告知用户点击已被捕获
                Console.WriteLine("修改按钮被点击，准备打开修改窗口");
                Cursor = Cursors.WaitCursor;

                // 获取选中行的ID
                long id = 0;
                try
                {
                    // 尝试获取ID值
                    object idValue = gridView1.GetRowCellValue(rowHandle, "Id");
                    if (idValue != null)
                    {
                        id = Convert.ToInt64(idValue);
                    }

                    if (id <= 0)
                    {
                        XtraMessageBox.Show("无效的记录ID", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"获取记录ID失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 获取产品名称用于日志记录
                string productName = "";
                try
                {
                    object nameValue = gridView1.GetRowCellValue(rowHandle, "Productitemname");
                    if (nameValue != null)
                    {
                        productName = nameValue.ToString();
                    }
                }
                catch { }

                Console.WriteLine($"准备修改产品: ID={id}, 名称={productName}");

                // 创建pinup窗体实例，传递产品ID
                pinup editForm = new pinup(id);

                // 显示修改窗体
                if (editForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果修改成功，刷新数据
                    Console.WriteLine("产品修改成功，刷新数据");
                    pageIndex = 1; // 重置为第一页
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"打开修改窗口异常: {ex.Message}\n{ex.StackTrace}");
                XtraMessageBox.Show($"打开修改窗口异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// 封装删除操作
        /// </summary>
        /// <param name="rowHandle">选中行的句柄</param>
        private async void DeleteSelectedRow(int rowHandle)
        {
            try
            {
                // 立即显示反馈，告知用户点击已被捕获
                Console.WriteLine("执行删除操作");
                Cursor = Cursors.WaitCursor;

                if (gridView1 == null || gridView1.RowCount == 0)
                {
                    XtraMessageBox.Show("没有可选择的数据记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (rowHandle < 0)
                {
                    XtraMessageBox.Show("请选择要删除的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                long id = 0;
                try
                {
                    // 尝试获取ID值
                    object idValue = gridView1.GetRowCellValue(rowHandle, "Id");
                    if (idValue != null)
                    {
                        id = Convert.ToInt64(idValue);
                    }

                    if (id <= 0)
                    {
                        XtraMessageBox.Show("无效的记录ID", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"获取记录ID失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 获取产品名称用于日志记录
                string productName = "";
                try
                {
                    object nameValue = gridView1.GetRowCellValue(rowHandle, "Productitemname");
                    if (nameValue != null)
                    {
                        productName = nameValue.ToString();
                    }
                }
                catch { }

                // 确认删除
                DialogResult result = XtraMessageBox.Show($"确定要删除该记录吗？\nID: {id}\n名称: {productName}", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result != DialogResult.Yes)
                    return;

                // 定义在外部作用域，以便在整个方法中访问
                bool isSuccess = false;
                string errorMessage = "删除失败";

                try
                {
                    // 显示等待提示
                    Cursor = Cursors.WaitCursor;

                    // 构建API URL
                    string url = $"api/ProductItem/DeleteProductItem?id={id}";
                    Console.WriteLine($"执行删除操作: ID={id}, 名称={productName}, URL={url}");

                    // 使用直接的HttpClient调用API
                    using (HttpClient client = new HttpClient())
                    {
                        // 设置基础地址
                        client.BaseAddress = new Uri(ApiBaseUrl);

                        // 发送PUT请求
                        HttpResponseMessage response = await client.PutAsync(url, null);

                        // 读取响应内容
                        string responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"删除操作响应: {responseContent}");

                        // 检查响应状态
                        if (response.IsSuccessStatusCode)
                        {
                            try
                            {
                                // 尝试解析JSON响应
                                JObject jObj = JObject.Parse(responseContent);
                                string code = jObj["Code"]?.ToString() ?? jObj["code"]?.ToString();

                                // 检查响应状态码
                                if (code == "200")
                                {
                                    isSuccess = true;
                                }
                                else
                                {
                                    // 获取错误消息
                                    errorMessage = jObj["Message"]?.ToString() ?? jObj["message"]?.ToString() ?? "删除失败";
                                }
                            }
                            catch (Exception parseEx)
                            {
                                Console.WriteLine($"解析删除响应异常: {parseEx.Message}");
                                errorMessage = $"解析响应失败: {parseEx.Message}";
                            }
                        }
                        else
                        {
                            errorMessage = $"请求失败，状态码: {response.StatusCode}";
                        }
                    }
                }
                finally
                {
                    // 恢复光标
                    Cursor = Cursors.Default;
                }

                // 根据结果执行相应操作
                if (isSuccess)
                {
                    XtraMessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 重置到第一页，并刷新数据
                    pageIndex = 1;
                    LoadData();
                }
                else
                {
                    XtraMessageBox.Show($"删除失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除操作异常: {ex.Message}\n{ex.StackTrace}");
                XtraMessageBox.Show($"删除操作发生异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 确保恢复光标
                Cursor = Cursors.Default;
            }
        }

        public void Update()
        {
            try
            {
                // 立即显示反馈，告知用户点击已被捕获
                Console.WriteLine("修改按钮被点击");
                Cursor = Cursors.WaitCursor;
                // 获取当前选中行对应的数据对象
                var view = gridView1;
                if (view == null || view.RowCount == 0)
                {
                    XtraMessageBox.Show("没有可选择的数据记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取选中行的句柄和ID
                int rowHandle = view.FocusedRowHandle;
                if (rowHandle < 0)
                {
                    XtraMessageBox.Show("请选择要修改的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                long id = 0;
                try
                {
                    // 尝试获取ID值
                    object idValue = view.GetRowCellValue(rowHandle, "Id");
                    if (idValue != null)
                    {
                        id = Convert.ToInt64(idValue);
                    }

                    if (id <= 0)
                    {
                        XtraMessageBox.Show("无效的记录ID", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"获取记录ID失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 获取产品名称用于日志记录
                string productName = "";
                try
                {
                    object nameValue = view.GetRowCellValue(rowHandle, "Productitemname");
                    if (nameValue != null)
                    {
                        productName = nameValue.ToString();
                    }
                }
                catch { }

                Console.WriteLine($"准备修改产品: ID={id}, 名称={productName}");

                try
                {
                    // 创建编辑窗体并传递产品ID
                    pinup editForm = new pinup(id);

                    // 显示窗体，如果修改成功则刷新数据
                    if (editForm.ShowDialog() == DialogResult.OK)
                    {
                        // 刷新数据
                        Console.WriteLine("修改成功，正在刷新数据...");
                        LoadData();
                    }
                    else
                    {
                        Console.WriteLine("用户取消了修改操作");
                    }
                }
                catch (Exception formEx)
                {
                    Console.WriteLine($"创建或显示编辑窗体异常: {formEx.Message}\n{formEx.StackTrace}");
                    XtraMessageBox.Show($"打开编辑窗口失败: {formEx.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"修改操作异常: {ex.Message}\n{ex.StackTrace}");
                XtraMessageBox.Show($"修改操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// 显示窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            // 创建并显示仪表板窗体
            daping daping = new daping();
            daping.ShowDialog();
        }
    }
}

// 自定义格式化器，将产品类型数字转换为文字
// 放在chanpin类之后，避免干扰设计器
public class CustomProductTypeFormatter : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg == null)
            return "-";
        
        if (arg is int productType)
        {
            switch (productType)
            {
                case 1: return "原材料";
                case 2: return "半成品";
                case 3: return "成品";
                case 4: return "其他";
                default: return $"{arg}";
            }
        }
        
        // 对于其他类型的值，尝试转换为整数
        if (int.TryParse(arg.ToString(), out int value))
        {
            switch (value)
            {
                case 1: return "原材料";
                case 2: return "半成品";
                case 3: return "成品";
                case 4: return "其他";
                default: return $"{arg}";
            }
        }
        
        return arg.ToString();
    }
}